<script setup lang="ts">import {ref, reactive, computed, onMounted} from 'vue'
// @ts-ignore
import {useProjectStore} from '@/stores/store'
import {storeToRefs} from 'pinia'
import GamepadKeyMapping from './GamepadKeyMapping.vue'
// 使用store
const projectStore = useProjectStore()
const {settings} = storeToRefs(projectStore)

declare global {
  interface Window {
    pywebview: {
      api: {
        insert_game_pads: (mode: object, keys: object, key_press_settings: any) => void,
        set_gamepad_mode: (mode: string | object) => void,
        set_gamepad_keys: (keys: any) => void,
        set_timed_key_press_settings: (settings: any) => void  // 添加定时按键设置的API
      }
    },
    debug: (text: string, type: any) => void // 输出信息至控制台
    printToTerm: (msg: string, level?: 'info' | 'error' | 'warn' | 'command' | 'debug' | 'success') => void // 输出信息至终端
    setTaskBar: (text: string, progress?: number) => void // 输出信息至任务栏
  }
}

// 定义可选的键盘按键
const keyboardKeys = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
  'Space', 'Enter', 'ESC', 'Tab', 'CapsLock', 'Shift', 'Ctrl', 'Alt',
  'LCtrl', 'RCtrl', 'LShift', 'RShift', 'LAlt', 'RAlt',
  '↑', '↓', '←', '→', // 方向键
  // 小键盘键位
  'Num0', 'Num1', 'Num2', 'Num3', 'Num4', 'Num5', 'Num6', 'Num7', 'Num8', 'Num9',
  'Num+', 'Num-', 'Num*', 'Num/', 'Num.', 'NumEnter', 'NumLock'
]

// 定义可选的鼠标按键
const mouseKeys = [
  '鼠标左键', // 左键
  '鼠标右键', // 右键
  '鼠标滚轮', // 中键
  '鼠标X1键',
  '鼠标X2键'
]

// 定义手柄按键
const gamepadKeys = [
  // 左摇杆
  'LJoy_up', 'LJoy_down', 'LJoy_left', 'LJoy_right',
  // 右摇杆
  'RJoy_up', 'RJoy_down', 'RJoy_left', 'RJoy_right',
  // 方向键
  'keyUp', 'keyDown', 'keyLeft', 'keyRight',
  // ABXY键
  'a', 'b', 'x', 'y',
  // 肩键
  'lb', 'rb', 'lt', 'rt',
  // 特殊按键
  'back', 'start'
]

// 定义操作模式快捷键
const modeKeys = settings.value.gamepad.mode

// 定义手柄按键映射
const gamepadMapping = settings.value.gamepad.keys

// 新增：定时按键功能状态
const timedKeyPressState = ref({
  interval: settings.value.timedKeyPress?.interval !== undefined ? settings.value.timedKeyPress.interval : 1000,
  targetKey: settings.value.timedKeyPress?.targetKey || '',
  hotkey: settings.value.timedKeyPress?.hotkey || '',
  scope: settings.value.timedKeyPress?.scope || 'global',
})

// 当前正在编辑的字段
const editingField = ref('')
const editingKeyIndex = ref(0) // 当前编辑的是第几个按键（支持多个按键）

// 插入两个游戏手柄
const insertTwoGamepads = () => {
  window.pywebview.api.insert_game_pads(modeKeys, gamepadMapping, timedKeyPressState.value)
}

// 开始编辑某个字段
const startEditing = (field: string, keyIndex: number = 0) => {
  editingField.value = field
  editingKeyIndex.value = keyIndex
}

// 更新模式快捷键
const updateModeKey = (mode: string, key: string) => {
  modeKeys[mode as keyof typeof modeKeys] = key
}

// 更新手柄按键映射
const updateGamepadKey = (mappingKey: string, key: string) => {
  // 确保gamepadMapping[mappingKey]是一个数组
  if (!Array.isArray(gamepadMapping[mappingKey])) {
    gamepadMapping[mappingKey] = [gamepadMapping[mappingKey] || '', '']
  }

  // 更新指定索引位置的按键
  gamepadMapping[mappingKey][editingKeyIndex.value] = key
}

// 新增：更新定时按键设置
const updateTimedKeyPressSetting = (field: string, value: string | number) => {
  // @ts-ignore
  timedKeyPressState.value[field] = value
}

// 保存所有设置到后端
const saveSettings = () => {
  // 发送模式快捷键设置
  window.pywebview.api.set_gamepad_mode({
    p1: modeKeys.p1,
    p2: modeKeys.p2,
    sync: modeKeys.sync,
    keyboard: modeKeys.keyboard,
    toggleP1: modeKeys.toggleP1,
    toggleP2: modeKeys.toggleP2
  })

  // 发送按键映射设置
  window.pywebview.api.set_gamepad_keys(gamepadMapping)

  // 保存定时按键功能设置
  window.pywebview.api.set_timed_key_press_settings(timedKeyPressState.value)
}

// 计算当前正在编辑的字段的值
const currentFieldValue = computed(() => {
  if (!editingField.value) return ''

  if (['p1', 'p2', 'sync', 'keyboard', 'toggleP1', 'toggleP2'].includes(editingField.value)) {
    return modeKeys[editingField.value as keyof typeof modeKeys]
  } else if (['interval', 'targetKey', 'hotkey'].includes(editingField.value)) {
    // @ts-ignore
    return timedKeyPressState.value[editingField.value] || ''
  } else {
    const mappingValue = gamepadMapping[editingField.value as keyof typeof gamepadMapping]
    // 如果是数组，返回指定索引的值；否则返回整个值（如果是字符串）
    if (Array.isArray(mappingValue)) {
      return mappingValue[editingKeyIndex.value] || ''
    } else {
      return editingKeyIndex.value === 0 ? mappingValue : ''
    }
  }
})

// 设置字段的值
const setFieldValue = (value: string) => {
  if (!editingField.value) return

  if (['p1', 'p2', 'sync', 'keyboard', 'toggleP1', 'toggleP2'].includes(editingField.value)) {
    updateModeKey(editingField.value, value)
  } else if (['interval', 'targetKey', 'hotkey'].includes(editingField.value)) {
    updateTimedKeyPressSetting(editingField.value, value)
  } else {
    updateGamepadKey(editingField.value, value)
  }

  editingField.value = ''
  editingKeyIndex.value = 0
}

// 获取所有已使用的键位
const usedKeys = computed(() => {
  const keys = new Set<string>()

  // 添加模式快捷键
  Object.values(modeKeys).forEach(key => keys.add(key as string))

  // 添加手柄映射键位
  Object.values(gamepadMapping).forEach(mapping => {
    if (Array.isArray(mapping)) {
      mapping.forEach(key => {
        if (key) keys.add(key as string)
      })
    } else if (mapping) {
      keys.add(mapping as string)
    }
  })

  // 添加定时按键热键
  if (timedKeyPressState.value.hotkey) {
    keys.add(timedKeyPressState.value.hotkey)
  }

  return keys
})

// 检查键位是否被使用
const isKeyUsed = (key: string) => {
  // 如果正在编辑的字段就是要设置的键，则不视为被占用
  if (currentFieldValue.value === key) {
    return false
  }
  return usedKeys.value.has(key)
}
</script>

<template>
  <div class="container mx-auto px-4 py-8 max-w-6xl">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-semibold text-gray-700">游戏手柄模拟器设置</h3>
      <button
          @click="saveSettings"
          class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-6 rounded-lg transition duration-200"
      >
        保存设置
      </button>
    </div>

    <div class="mb-8 p-6 bg-white rounded-lg shadow-md">
      <button
          @click="insertTwoGamepads"
          class="bg-green-500 hover:bg-green-600 text-white font-medium py-3 px-6 rounded-lg transition duration-200"
      >
        插入两个游戏手柄
      </button>
    </div>

    <div class="mb-8 p-6 bg-white rounded-lg shadow-md">
      <h3 class="text-xl font-semibold mb-4 text-gray-700">操作模式快捷键设置</h3>
      <div class="grid grid-cols-[repeat(auto-fit,_minmax(400px,_1fr))] gap-4">
        <div class="flex items-center justify-between px-3 bg-yellow-100 rounded-lg">
          <span class="text-gray-700">单独操作P1:</span>
          <button
              @click="startEditing('p1')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ modeKeys.p1 || '未设置' }}
          </button>
        </div>
        <div class="flex items-center justify-between px-3 bg-yellow-100 rounded-lg">
          <span class="text-gray-700">单独操作P2:</span>
          <button
              @click="startEditing('p2')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ modeKeys.p2 || '未设置' }}
          </button>
        </div>
        <div class="flex items-center justify-between px-3 bg-yellow-100 rounded-lg">
          <span class="text-gray-700">同步操作P1和P2:</span>
          <button
              @click="startEditing('sync')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ modeKeys.sync || '未设置' }}
          </button>
        </div>
        <div class="flex items-center justify-between px-3 bg-yellow-100 rounded-lg">
          <span class="text-gray-700">恢复键鼠模式:</span>
          <button
              @click="startEditing('keyboard')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ modeKeys.keyboard || '未设置' }}
          </button>
        </div>
        <div class="flex items-center justify-between px-3 bg-yellow-100 rounded-lg">
          <span class="text-gray-700">切换P1:</span>
          <button
              @click="startEditing('toggleP1')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ modeKeys.toggleP1 || '未设置' }}
          </button>
        </div>
        <div class="flex items-center justify-between px-3 bg-yellow-100 rounded-lg">
          <span class="text-gray-700">切换P2:</span>
          <button
              @click="startEditing('toggleP2')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ modeKeys.toggleP2 || '未设置' }}
          </button>
        </div>
      </div>
    </div>

    <div class="mb-8 p-6 bg-white rounded-lg shadow-md">
      <h3 class="text-xl font-semibold mb-4 text-gray-700">手柄按键映射设置</h3>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">

        <!-- 左摇杆 -->
        <div class="border border-blue-500 rounded-lg p-4">
          <h4 class="font-medium mb-3 text-gray-700">左摇杆 (控制移动)</h4>
          <div class="space-y-2">
            <GamepadKeyMapping
                label="上"
                mapping-key="LJoy_up"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="左"
                mapping-key="LJoy_left"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="下"
                mapping-key="LJoy_down"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="右"
                mapping-key="LJoy_right"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />

          </div>
        </div>

        <!-- 右侧摇杆 -->
        <div class="border border-blue-500 rounded-lg p-4">
          <h4 class="font-medium mb-3 text-gray-700">右摇杆 (控制视角)</h4>
          <div class="space-y-2">
            <GamepadKeyMapping
                label="上"
                mapping-key="RJoy_up"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="左"
                mapping-key="RJoy_left"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="下"
                mapping-key="RJoy_down"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="右"
                mapping-key="RJoy_right"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
          </div>
        </div>

        <!-- 方向键 -->
        <div class="border border-blue-500 rounded-lg p-4">
          <h4 class="font-medium mb-3 text-gray-700">方向键（手柄按键）</h4>
          <div class="space-y-2">
            <GamepadKeyMapping
                label="上"
                mapping-key="keyUp"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="左"
                mapping-key="keyLeft"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="下"
                mapping-key="keyDown"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="右"
                mapping-key="keyRight"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
          </div>
        </div>

        <!-- ABXY 按键 -->
        <div class="border border-blue-500 rounded-lg p-4">
          <h4 class="font-medium mb-3 text-gray-700">ABXY 按键</h4>
          <div class="space-y-2">
            <GamepadKeyMapping
                label="A"
                mapping-key="a"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="B"
                mapping-key="b"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="X"
                mapping-key="x"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="Y"
                mapping-key="y"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
          </div>
        </div>

        <!-- 肩键 -->
        <div class="border border-blue-500 rounded-lg p-4">
          <h4 class="font-medium mb-3 text-gray-700">肩键</h4>
          <div class="space-y-2">
            <GamepadKeyMapping
                label="LB"
                mapping-key="lb"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="RB"
                mapping-key="rb"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="LT"
                mapping-key="lt"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="RT"
                mapping-key="rt"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
          </div>
        </div>

        <!-- 特殊按键 -->
        <div class="border border-blue-500 rounded-lg p-4">
          <h4 class="font-medium mb-3 text-gray-700">特殊按键</h4>
          <div class="space-y-2">
            <GamepadKeyMapping
                label="Back"
                mapping-key="back"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
            <GamepadKeyMapping
                label="Start"
                mapping-key="start"
                :gamepad-mapping="gamepadMapping"
                @edit="startEditing"
            />
          </div>
        </div>

      </div>
    </div>

    <!-- 新增：定时按键功能设置 -->
    <div class="mb-8 p-6 bg-white rounded-lg shadow-md">
      <h3 class="text-xl font-semibold mb-4 text-gray-700">定时按键功能设置</h3>
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="flex items-center justify-between px-3 bg-purple-100 rounded-lg"
             title="作用域为P1或P2时只支持手柄按键，全局时支持所有按键；选择P1则只有第1个手柄定时按键；选择P2则只有第2个手柄定时按键">
          <span class="text-gray-700">作用域:</span>
          <select
              v-model="timedKeyPressState.scope"
              class="bg-blue-100 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center border border-blue-300"
          >
            <option value="global">全局</option>
            <option value="p1">P1</option>
            <option value="p2">P2</option>
          </select>
        </div>
        <div class="flex items-center justify-between px-3 bg-purple-100 rounded-lg">
          <span class="text-gray-700" title="间隔时间为0，则长按目标按键">间隔时间(ms):</span>
          <input
              type="number"
              min="100"
              max="10000"
              step="100"
              v-model.number="timedKeyPressState.interval"
              class="bg-blue-100 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center border border-blue-300"
          />
        </div>
        <div class="flex items-center justify-between px-3 bg-purple-100 rounded-lg"
             title="作用域为P1或P2时只支持手柄按键，全局时支持所有按键">
          <span class="text-gray-700">目标按键:</span>
          <button
              @click="startEditing('targetKey')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ timedKeyPressState.targetKey || '未设置' }}
          </button>
        </div>
        <div class="flex items-center justify-between px-3 bg-purple-100 rounded-lg">
          <span class="text-gray-700">快捷键:</span>
          <button
              @click="startEditing('hotkey')"
              class="bg-blue-100 hover:bg-blue-200 text-gray-800 py-1 px-3 rounded min-w-[100px] w-[100px] text-center cursor-pointer transition duration-200"
          >
            {{ timedKeyPressState.hotkey || '未设置' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 按键设置提示 -->
    <div
        v-if="editingField"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-5xl max-h-[80vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold">选择按键</h3>
          <div class="flex space-x-2">
            <button
                @click="setFieldValue('')"
                class="bg-red-500 hover:bg-red-600 text-white py-2 px-4 rounded transition duration-200"
            >
              删除当前快捷键
            </button>
            <button
                @click="editingField = ''"
                class="bg-gray-500 hover:bg-gray-600 text-white py-2 px-4 rounded transition duration-200"
            >
              取消
            </button>
          </div>
        </div>

        <!-- 对于目标按键，显示所有按键选项 -->
        <div v-if="editingField === 'targetKey'" class="mb-4">
          <h4 class="font-medium mb-2">键盘按键</h4>
          <div class="grid grid-cols-10 gap-2">
            <button
                v-for="key in keyboardKeys"
                :key="'kb-' + key"
                @click="!isKeyUsed(key) && setFieldValue(key)"
                :disabled="isKeyUsed(key)"
                :class="[
                'py-2 px-1 text-sm rounded border',
                isKeyUsed(key)
                  ? 'bg-gray-200 text-gray-500 border-gray-300 cursor-not-allowed'
                  : currentFieldValue === key
                    ? 'bg-blue-500 text-white border-blue-500'
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-100'
              ]"
            >
              {{ key }}
            </button>
          </div>
        </div>

        <div v-if="editingField === 'targetKey'" class="mb-4">
          <h4 class="font-medium mb-2">鼠标按键</h4>
          <div class="grid grid-cols-10 gap-2">
            <button
                v-for="key in mouseKeys"
                :key="'mouse-' + key"
                @click="!isKeyUsed(key) && setFieldValue(key)"
                :disabled="isKeyUsed(key)"
                :class="[
                'py-2 px-1 text-sm rounded border',
                isKeyUsed(key)
                  ? 'bg-gray-200 text-gray-500 border-gray-300 cursor-not-allowed'
                  : currentFieldValue === key
                    ? 'bg-blue-500 text-white border-blue-500'
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-100'
              ]"
            >
              {{ key }}
            </button>
          </div>
        </div>

        <div v-if="editingField === 'targetKey'" class="mb-6">
          <h4 class="font-medium mb-2">手柄按键</h4>
          <div class="grid grid-cols-10 gap-2">
            <button
                v-for="key in gamepadKeys"
                :key="'gamepad-' + key"
                @click="!isKeyUsed(key) && setFieldValue(key)"
                :disabled="isKeyUsed(key)"
                :class="[
                'py-2 px-1 text-sm rounded border',
                isKeyUsed(key)
                  ? 'bg-gray-200 text-gray-500 border-gray-300 cursor-not-allowed'
                  : currentFieldValue === key
                    ? 'bg-blue-500 text-white border-blue-500'
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-100'
              ]"
            >
              {{ key }}
            </button>
          </div>
        </div>

        <!-- 对于其他所有快捷键设置，同时显示键盘和鼠标按键 -->
        <div v-else>
          <div class="mb-4">
            <h4 class="font-medium mb-2">键盘按键</h4>
            <div class="grid grid-cols-10 gap-2">
              <button
                  v-for="key in keyboardKeys"
                  :key="'kb-' + key"
                  @click="!isKeyUsed(key) && setFieldValue(key)"
                  :disabled="isKeyUsed(key)"
                  :class="[
                  'py-2 px-1 text-sm rounded border',
                  isKeyUsed(key)
                    ? 'bg-gray-200 text-gray-500 border-gray-300 cursor-not-allowed'
                    : currentFieldValue === key
                      ? 'bg-blue-500 text-white border-blue-500'
                      : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-100'
                ]"
              >
                {{ key }}
              </button>
            </div>
          </div>

          <div class="mb-6">
            <h4 class="font-medium mb-2">鼠标按键</h4>
            <div class="grid grid-cols-10 gap-2">
              <button
                  v-for="key in mouseKeys"
                  :key="'mouse-' + key"
                  @click="!isKeyUsed(key) && setFieldValue(key)"
                  :disabled="isKeyUsed(key)"
                  :class="[
                  'py-2 px-1 text-sm rounded border',
                  isKeyUsed(key)
                    ? 'bg-gray-200 text-gray-500 border-gray-300 cursor-not-allowed'
                    : currentFieldValue === key
                      ? 'bg-blue-500 text-white border-blue-500'
                      : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-100'
                ]"
              >
                {{ key }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>
